extends Sprite2D

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")

var target_position = Vector2(50, 50)  # 目标位置，可以根据需要进行修改  
var rotation_speed = 0.5  # 旋转速度，可以根据需要进行调整 

func set_target_position(lposition):
	#print(lposition)
	target_position = lposition
	
func _process(delta):  
	var direction_to_target = (target_position - global_transform.origin).normalized()  # 计算到目标的方向向量  
	var current_direction = Vector2(0, 1).rotated(rotation)  # 当前方向  
	var angle_diff = direction_to_target.angle_to(current_direction)  # 计算角度差  
	
	# 防抖动
	var angle_diff2 = abs(angle_diff)
	if angle_diff2>0:
		if angle_diff2 < 0.1:
			return
		if PI-angle_diff2<0.1:
			return
	 
	# 根据角度差调整旋转，使物体逐渐转向目标位置  
	rotation += angle_diff * delta * rotation_speed
	
	# 保持旋转角度在 2*PI以内
	if rotation > 2*PI:
		rotation -= 2*PI
	elif rotation < -2*PI:
		rotation += 2*PI
	print(rotation)
 
